package com.renhui.android.handwriting.handler;

public class Looper {

    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<>();
    final MessageQueue mQueue;

    private Looper() {
         // 初始化消息队列
        mQueue = new MessageQueue();
    }

    public static void prepare() {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be create per thread");
        }
        sThreadLocal.set(new Looper());
    }

    public static Looper myLooper() {
        return sThreadLocal.get();
    }

    public static void loop() {
        Looper looper = sThreadLocal.get();
        if (looper != null) {
            MessageQueue messageQueue = looper.mQueue;
            while (true) {
                Message msg = messageQueue.next();
                if (msg != null) {
                    msg.target.dispatchMessage(msg);
                }
            }
        }
    }
}
